//
//  MainViewController.swift
//  HMWeibo007
//
//  Created by TTang on 15/6/28.
//  Copyright © 2015年 shanyu. All rights reserved.
//

import UIKit

class MainViewController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()

        //使用KVC替换系统的tabBar
        let tb = MainTabBar()
        tb.composedButton.addTarget(self, action: "composedButtonClicked", forControlEvents: UIControlEvents.TouchUpInside)
        setValue(tb, forKeyPath: "tabBar")
        
         addChildViewControllers()
        
    }
    
    func composedButtonClicked(){
      print(__FUNCTION__)
    }
    
    func addChildViewControllers() {
        
          //从json中加载各控制器信息
          let path = NSBundle.mainBundle().pathForResource("MainVCSetting.json", ofType: nil)!
          let data = NSData(contentsOfFile: path)!
          //Xcode7.0中json的序列化需要抛异常
          do {
            
            let array = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments)
            //遍历数组添加控制器
            for dict in array as! [[String:String]] {
             
              addChildViewController(dict["vcName"]!, title: dict["title"]!, imageName: dict["imageName"]!)
             }
        
          }catch(_){
            //异常处理
            addChildViewController("HomeTableViewController", title: "首页", imageName: "tabbar_home")
            addChildViewController("MessageTableViewController", title: "消息", imageName: "tabbar_message_center")
            addChildViewController("DiscoverTableViewController", title: "发现", imageName: "tabbar_discover")
            addChildViewController("ProfileTableViewController", title: "我", imageName: "tabbar_profile")
          }
        
        
}

    func addChildViewController(vcName:String,title:String,imageName:String) {
        
        tabBar.tintColor = UIColor.orangeColor()
        //从字典中获取项目名
        let ns = NSBundle.mainBundle().infoDictionary!["CFBundleExecutable"] as! String
        //字符串转为类
        let cls : AnyClass = NSClassFromString(ns + "." + vcName)!
        //实例化控制器
        let  vc = cls.new() as! UIViewController
        
        vc.title = title
        vc.tabBarItem.image = UIImage(named: imageName)
        vc.tabBarItem.selectedImage = UIImage(named: imageName + "_highlighted")
        
        let nav = UINavigationController(rootViewController: vc)
        addChildViewController(nav)
    }

    
    
    
}
